package com.zsc.edu.testbroadcastreceiver;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    NetStatusBroadcastReceiver mNetStatusBroadcastReceiver;

    // 本地广播管理者，用于发送和注册本地广播
    LocalBroadcastManager mLocalBroadcastManager;
    // 本地广播接收者，用于接收本地广播
    LocalBroadcastReceiver mLocalBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 构造 NetStatusBroadcastReceiver
        mNetStatusBroadcastReceiver = new NetStatusBroadcastReceiver();

        // 利用IntentFilter，指定需要接收的广播的行为
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        // 注册广播
        registerReceiver(mNetStatusBroadcastReceiver, intentFilter);

        // 得到本地广播管理器的实例
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 注册本地广播
        // 利用IntentFilter，指定需要接收的广播的行为
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction("com.zsc.edu.testbroadcastsender.LOCAL_BROADCAST");
        mLocalBroadcastReceiver = new LocalBroadcastReceiver();

        // 使用 本地广播管理器 注册本地广播
        mLocalBroadcastManager.registerReceiver(mLocalBroadcastReceiver, intentFilter1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetStatusBroadcastReceiver);
        mLocalBroadcastManager.unregisterReceiver(mLocalBroadcastReceiver);
    }
}